<template>
  <div>
    <el-form :inline="true" @submit.prevent>
      <el-form-item>
        <el-input v-model="query.keyword" placeholder="搜索菜单名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-select v-model="query.sortBy" placeholder="排序字段" style="width:140px">
          <el-option label="ID" value="id"/>
          <el-option label="名称" value="name"/>
          <el-option label="排序" value="sortOrder"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select v-model="query.sortOrder" style="width:120px">
          <el-option label="降序" value="desc"/>
          <el-option label="升序" value="asc"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="load">查询</el-button>
        <el-button @click="openCreate">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="list" style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80"/>
      <el-table-column prop="name" label="菜单名称"/>
      <el-table-column prop="path" label="路径"/>
      <el-table-column prop="component" label="组件"/>
      <el-table-column prop="sortOrder" label="排序"/>
      <el-table-column prop="icon" label="图标"/>
      <el-table-column prop="visible" label="可见">
        <template #default="scope">
          <el-tag :type="scope.row.visible ? 'success' : 'danger'">
            {{ scope.row.visible ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="scope">
          <el-button link @click="openEdit(scope.row)">编辑</el-button>
          <el-button link type="danger" @click="remove(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="query.page"
      v-model:page-size="query.size"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      :pager-count="5"
      :page-size-options="[10, 20, 50, 100]"
      :total-text="`共 ${total} 条`"
      :page-size-text="'条/页'"
      :goto-text="'前往'"
      :page-text="'页'"
      :prev-text="'上一页'"
      :next-text="'下一页'"
      @size-change="load"
      @current-change="load"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑菜单' : '新增菜单'" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="父菜单" prop="parentId">
          <el-select v-model="form.parentId" placeholder="请选择父菜单" clearable>
            <el-option label="无（顶级菜单）" :value="null"/>
            <el-option 
              v-for="menu in parentMenus" 
              :key="menu.id" 
              :label="menu.name" 
              :value="menu.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜单名称"/>
        </el-form-item>
        <el-form-item label="路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入路径"/>
        </el-form-item>
        <el-form-item label="组件" prop="component">
          <el-input v-model="form.component" placeholder="请输入组件名称"/>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input-number v-model="form.sortOrder" :min="0" placeholder="排序"/>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入图标名称"/>
        </el-form-item>
        <el-form-item label="可见" prop="visible">
          <el-switch v-model="form.visible"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useI18n } from 'vue-i18n'
import request from '../utils/request'

const { t } = useI18n()

const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

const query = reactive({
  page: 1,
  size: 10,
  keyword: '',
  sortBy: 'id',
  sortOrder: 'desc'
})

const form = reactive({
  id: null,
  parentId: null,
  name: '',
  path: '',
  component: '',
  sortOrder: 0,
  icon: '',
  visible: true
})

const list = ref([])
const total = ref(0)
const parentMenus = ref([])

const rules = {
  name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }]
}

async function load() {
  loading.value = true
  try {
    const { data } = await request.get('/api/menus', { params: query })
    list.value = data.data.records
    total.value = data.data.total
    
    // 加载父菜单选项
    const parentData = await request.get('/api/menus', { params: { page: 1, size: 1000 } })
    parentMenus.value = parentData.data.data.records
  } catch (error) {
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

function openCreate() {
  isEdit.value = false
  Object.assign(form, {
    id: null,
    parentId: null,
    name: '',
    path: '',
    component: '',
    sortOrder: 0,
    icon: '',
    visible: true
  })
  dialogVisible.value = true
}

function openEdit(row) {
  isEdit.value = true
  Object.assign(form, row)
  dialogVisible.value = true
}

async function save() {
  if (!formRef.value) return
  await formRef.value.validate()
  
  try {
    if (isEdit.value) {
      await request.put(`/api/menus/${form.id}`, form)
      ElMessage.success('更新成功')
    } else {
      await request.post('/api/menus', form)
      ElMessage.success('创建成功')
    }
    dialogVisible.value = false
    load()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  }
}

async function remove(id) {
  try {
    await ElMessageBox.confirm('确定要删除这个菜单吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await request.delete(`/api/menus/${id}`)
    ElMessage.success('删除成功')
    load()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  load()
})
</script>

<style scoped>
.el-form--inline .el-form-item {
  margin-right: 16px;
}
</style>
